﻿using System;
using Microsoft.AspNetCore.Mvc;
using Nxg.Blog.Core;
using Nxg.Blog.Core.Commands;
using Nxg.Blog.Core.Commands.Posts;
using Nxg.Blog.Core.ViewProjections.Admin;

namespace Nxg.Blog.Web.Controllers
{
    public class PostController : SecureController
    {
        private readonly ICommandInvokerFactory _commandInvokerFactory;
        public PostController(IViewProjectionFactory viewProjectionFactory, ICommandInvokerFactory commandInvokerFactory) : base(viewProjectionFactory)
        {
            _commandInvokerFactory = commandInvokerFactory;
        }

        [HttpGet("/post/")]
        [HttpGet("post/{page}")]
        public IActionResult Index(int page = 1)
        {
            var model =
                _viewProjectionFactory.Get<AllBlogPostsBindingModel, AllBlogPostsViewModel>(new AllBlogPostsBindingModel()
                {
                    Page = page,
                    Take = 15
                });
            return View(model);
        }

        [HttpGet("post/new")]
        public IActionResult New()
        {
            return View(new NewPostCommand());
        }


        [HttpGet("post/delete/{blogPostId}")]
        public IActionResult Delete(int blogPostId)
        {
            _commandInvokerFactory.Handle<DeletePostCommand, CommandResult>(new DeletePostCommand { PostId = blogPostId });
            return RedirectToAction("Index");
        }

        [HttpPost]
        public IActionResult New([FromForm] NewPostCommand command)
        {
            command.Author = CurrentUser;
            var commandResult = _commandInvokerFactory.Handle<NewPostCommand, CommandResult>(command);

            if (commandResult.Success)
            {
                return RedirectToAction("Index");
            }
            ViewBag.Tips = string.Join(',', commandResult.GetErrors());
            return View(command);
        }

        [HttpPost]
        public CommandResult<string> Slug([FromBody] GetSlugCommand command)
        {
            return _commandInvokerFactory.Handle<GetSlugCommand, CommandResult<string>>(command);
        }

        [HttpGet("post/edit/{blogPostId}")]
        public IActionResult Edit(int blogPostId)
        {
            var model =
                _viewProjectionFactory.Get<BlogPostEditBindingModel, NewPostCommand>(
                    new BlogPostEditBindingModel
                    {
                        PostId = blogPostId
                    }
                );
            return View("New", model);
        }
    }
}